package com.zhaosc.invoke;

import java.rmi.RemoteException;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.zhaosc.configbean.Reference;
import com.zhaosc.loadbalance.LoadBalance;
import com.zhaosc.loadbalance.NodeInfo;
import com.zhaosc.rmi.RmiUtil;
import com.zhaosc.rmi.SoaRmi;

public class RmiInvoke implements Invoke{

	@Override
	public String invoke(Invocation invocation) {
		
		try {
			List<String> registryInfo=invocation.getReference().getRegistryInfo();
			
			Reference reference=invocation.getReference();
			String loadBalanceKey=reference.getLoadBalance();
			LoadBalance loadBalance=reference.getLoadBalances().get(loadBalanceKey);
			
			NodeInfo nodeInfo=loadBalance.doSelect(registryInfo);
			
			JSONObject sendParam=new JSONObject(); 
			sendParam.put("methodName", invocation.getMethod().getName());
			sendParam.put("methodParams", invocation.getParams());
			sendParam.put("paramTypes", invocation.getMethod().getParameterTypes());
			
			RmiUtil rmi=new RmiUtil();
			SoaRmi soarmi=rmi.startRmiClient(nodeInfo,"zhaoRmi");

			return soarmi.invoke(sendParam.toJSONString());
		
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	
	}

}
